#coding: utf8
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
import datetime
import sys
import os.path
import logging.config
import datetime
import MySQLdb
import time
from decimal import *
from email.header import Header

class AttrMail(object):
    strFrom=None
    lTo=None
    strSubject=None
    strMsgASCII=None
    strMsgHTML=None
    strHTMLFile=None
    """doble lista de imagenes y IDs relacionados en el html"""
    listImages=[]
    strSMTP=None
    strUser=None
    strPwd=None

    def __str__( self ):
        return str("toString no implementado")

class CampaignRestaurant(object):
    campaign=None
    id_Rest=None
    rest_name=None
    email=None
    score=None
    score_presence=None
    score_opinions=None
    score_activity=None
    posts30=None
    post1_net=None
    post1_title=None
    post1_date=None
    post1_score=None
    post1_text=None
    post2_net=None
    post2_title=None
    post2_date=None
    post2_score=None
    post2_text=None

    def __str__( self ):
        return str("campaign:"+str(self.campaign)+ "id_Rest:"+str(self.id_Rest)+"self.rest_name:"+self.rest_name+"self.email:"+self.email +\
                   "self.score:"+str(self.score)+"self.score_presence:"+str(self.score_presence)+"self.score_opinions:"+str(self.score_opinions) +\
                   "self.score_activity:"+str(self.score_activity)+"self.posts30:"+str(self.posts30)+"self.post1_net:"+str(self.post1_net) +\
                   "self.post1_title:"+str(self.post1_title)+"self.post1_date:"+str(self.post1_date)+"self.post1_score:"+str(self.post1_score) +\
                   "self.post1_text:"+str(self.post1_text)+"self.post2_net:"+str(self.post2_net)+"self.post2_title:"+str(self.post2_title) +\
                   "self.post2_date:"+str(self.post2_date)+"self.post2_score:"+str(self.post2_score)+"self.post2_text:"+self.post2_text)


class DB(object):
    host = "mysql1.alwaysdata.com"
    user = "62465_jmgost"
    passw = "sygnium"
    skema = "freshbuzzing_1"

    log=None
    
    def __init__(self, log):
        self.log = log

    def connectDB(self):
        try:
            self.db = MySQLdb.connect(self.host,self.user,self.passw,self.skema)
            self.db.set_character_set('utf8')
        except Exception,e:
            self.log.error("Error al conectar a base de datos MySQLdb.connect: " + str(e))
            return False
        return True


    def disconnectDB(self):
        self.db
        self.db.close()
        
        
    def getCursor(self):
        try:
            cursor = self.db.cursor()
            cursor.execute('SET NAMES utf8;')
            cursor.execute('SET CHARACTER SET utf8;')
            cursor.execute('SET character_set_connection=utf8;')
            return cursor
        except Exception,e:
            self.log.error("Error al crear cursor MySQLdb:  " + str(e))


    def getCampaingsDetails(self,campaign):
        limit='LIMIT 290'
        list=[]
        cur1=None
        cur2=None

        try:        
            if campaign==0 or campaign==1:
                sql0="SELECT mcamp.ID_CAMPAIGN,mcamp.ID_RESTAURANT,mrest.DS_REST_NAME,mcamp.DS_EMAIL,h.NUM_SCORE_GLOBAL,\
                          NUM_SCORE_PRESENCE, NUM_SCORE_OPINIONS, NUM_SCORE_ACTIVITY \
                      FROM MAST_CAMPAINGS mcamp, MAST_RESTAURANTS mrest, HIST_SCORE_GLOBAL h \
                      WHERE mcamp.ID_RESTAURANT=mrest.ID_RESTAURANT and mcamp.ID_CAMPAIGN=%s and mcamp.DT_SENT is null and \
                          h.ID_RESTAURANT=mcamp.ID_RESTAURANT and \
                          h.DT_SCORE = (select max(DT_SCORE) from HIST_SCORE_GLOBAL h1 where h1.ID_RESTAURANT=h.ID_RESTAURANT)" %str(campaign)
                sql1="order by DT_SENT asc %s" % (limit)
                sql = sql0 + sql1
                cur1 = self.getCursor()
                cur1.execute(sql)
                for row in cur1.fetchall():
                    campaignRest = CampaignRestaurant()
                    campaignRest.campaign=row[0]
                    campaignRest.id_Rest=row[1]
                    campaignRest.rest_name=row[2]
                    campaignRest.email=row[3]
                    campaignRest.score=row[4]
                    campaignRest.score_presence=row[5]
                    campaignRest.score_opinions=row[6]
                    campaignRest.score_activity==row[7]
                    list.append(campaignRest)
                self.db.commit()
            elif campaign==2 or campaign==3 or campaign==4 or campaign==5:
                #get basic data first
                sql0="SELECT mcamp.ID_CAMPAIGN,mcamp.ID_RESTAURANT,mrest.DS_REST_NAME,mcamp.DS_EMAIL,lvalues.NUM_VALUE 'POSTS', \
                          h.NUM_SCORE_GLOBAL,NUM_SCORE_PRESENCE, NUM_SCORE_OPINIONS, NUM_SCORE_ACTIVITY \
                      FROM MAST_CAMPAINGS mcamp, MAST_RESTAURANTS mrest,LAST_VALUES_RESTAURANT lvalues, HIST_SCORE_GLOBAL h \
                      WHERE mcamp.ID_RESTAURANT=mrest.ID_RESTAURANT and mcamp.ID_CAMPAIGN=%s and mcamp.DT_SENT is null and \
                          h.ID_RESTAURANT=mcamp.ID_RESTAURANT and lvalues.ID_RESTAURANT=mcamp.ID_RESTAURANT and lvalues.ID_PARAMETER = 'VAR_POSTS_30D' and \
                          h.DT_SCORE = (select max(DT_SCORE) from HIST_SCORE_GLOBAL h1 where h1.ID_RESTAURANT=h.ID_RESTAURANT)" %str(campaign)
                sql1="order by DT_SENT asc %s" % (limit)
                sql = sql0 + sql1
                cur1 = self.getCursor()
                cur1.execute(sql)
                for row in cur1.fetchall():
                    campaignRest = CampaignRestaurant()
                    campaignRest.campaign=row[0]
                    campaignRest.id_Rest=row[1]
                    campaignRest.rest_name=row[2]
                    campaignRest.email=row[3]
                    campaignRest.posts30=row[4]
                    campaignRest.score=row[5]
                    campaignRest.score_presence=row[6]
                    campaignRest.score_opinions=row[7]
                    campaignRest.score_activity=row[8]
                    #get 2 posts data
                    sql0="SELECT  'ATRAPALO' as CHANNEL, h.DT_POST, h.NUM_SCORE, NULL as DS_TITLE_POST, DS_POST from HIST_POSTS_ATRAPALO h where h.ID_RESTAURANT=%s " + \
                          " UNION SELECT  'SALIR' as CHANNEL, h.DT_POST, h.NUM_SCORE*2, DS_TITLE_POST, DS_POST from HIST_POSTS_SALIR h where  h.ID_RESTAURANT=%s " + \
                          " UNION SELECT 'YELP' as CHANNEL, h.DT_POST, h.NUM_SCORE*2, NULL as DS_TITLE_POST, DS_POST FROM HIST_POSTS_YELP h where h.ID_RESTAURANT=%s " + \
                          " UNION SELECT 'TRIPADVISOR' as CHANNEL, h.DT_POST, h.NUM_SCORE*2, DS_TITLE_POST, DS_POST FROM HIST_POSTS_TRIPADVISOR h where h.ID_RESTAURANT=%s " + \
                          " UNION SELECT 'RESTALO' as CHANNEL, h.DT_POST, h.NUM_SCORE, NULL as DS_TITLE_POST, DS_POST FROM HIST_POSTS_RESTALO h where h.ID_RESTAURANT=%s " + \
                          " UNION SELECT 'TENEDOR' as CHANNEL, h.DT_POST, h.NUM_SCORE, NULL as DS_TITLE_POST, DS_POST FROM HIST_POSTS_TENEDOR h where  h.ID_RESTAURANT=%s and ds_post != 'No hay opiniones' and trim(ds_post) !=''" + \
                          " order by DT_POST desc limit 2"
                    
                    cur2 = self.getCursor()
                    cur2.execute(sql0,(campaignRest.id_Rest,campaignRest.id_Rest,campaignRest.id_Rest,campaignRest.id_Rest,campaignRest.id_Rest,campaignRest.id_Rest))
                    count=1
                    row1=None
                    for row1 in cur2.fetchall():
                        if count==1:
                            campaignRest.post1_net=row1[0]
                            campaignRest.post1_date=row1[1]
                            campaignRest.post1_score=row1[2]
                            campaignRest.post1_title=row1[3]
                            campaignRest.post1_text=row1[4]
                        else:
                            campaignRest.post2_net=row1[0]
                            campaignRest.post2_date=row1[1]
                            campaignRest.post2_score=row1[2]
                            campaignRest.post2_title=row1[3]
                            campaignRest.post2_text=row1[4]                                                        
                        count=count+1
                    list.append(campaignRest)
                    #self.log.debug("campaign:"+str(campaignRest))
                self.db.commit()   
            elif campaign==7:
                #get basic data first
                sql0="SELECT mcamp.ID_CAMPAIGN,mcamp.ID_RESTAURANT,mrest.DS_REST_NAME,mcamp.DS_EMAIL \
                        FROM MAST_CAMPAINGS mcamp, MAST_RESTAURANTS mrest \
                        WHERE mcamp.ID_RESTAURANT=mrest.ID_RESTAURANT and mcamp.ID_CAMPAIGN=%s and mcamp.DT_SENT is null " %str(campaign)
                sql1="order by DT_SENT asc %s" % (limit)
                sql = sql0 + sql1
                cur1 = self.getCursor()
                cur1.execute(sql)  
                for row in cur1.fetchall():
                    campaignRest = CampaignRestaurant()
                    campaignRest.campaign=row[0]
                    campaignRest.id_Rest=row[1]
                    campaignRest.rest_name=row[2]
                    campaignRest.email=row[3]
                    list.append(campaignRest)
                self.db.commit()                  
        except Exception,e:
            self.log.error("Error al ejecutar sentencia SQL en getCampaingsDetails:  " + str(e))
            self.db.rollback()
        else:
            self.db.commit()
        finally:
            if cur1 is not None:
                cur1.close()
            if cur2 is not None:
                cur2.close()                
            return list


    def campaignSent(self,campaign,idRest):


        sql="UPDATE MAST_CAMPAINGS SET DT_SENT=NOW()WHERE ID_CAMPAIGN=%s AND ID_RESTAURANT=%s" 
        
        try:
            cur=self.getCursor()
            cur.execute(sql,(campaign,idRest))
            self.db.commit()
                
        except Exception,e:
            self.log.error("Error al ejecutar sentencia SQL en campaignSent:  " + str(e))
            self.db.rollback()
        else:
            self.db.commit()
        finally:
            cur.close()   

    def __del__(self):
        self.db.close()


class EmailMarketing(object):


    log=None
   
    def __init__(self, log):
        self.log = log

    def prepareEmail(self,l):
        try:
            if l.campaign is None or l.id_Rest is None  or l.rest_name is None or l.email is None:
                return
                       
            attrMail = AttrMail()
            attrMail.strFrom='irestauranting@irestauranting.com'
            attrMail.lTo=[l.email]
            #attrMail.lTo=['pcocko@sygnium.com','jmgost@sygnium.com','pcocko@gmail.com','jmgost@gmail.com','pcocko@adasasistemas.com']
            #attrMail.lTo=['jmgost@gmail.com','pcocko@gmail.com']
            #attrMail.lTo=['jmgost@gmail.com','jmgost@sygnium.com','pcocko@gmail.com','pcocko@sygnium.com']
            attrMail.strSMTP='smtp.alwaysdata.com'
            attrMail.strUser='irestauranting@irestauranting.com'
            attrMail.strPwd='sygnium2013'
    
            if str(l.campaign)=='0' or str(l.campaign)=='1':
               attrMail=self.__prepareEmailCamp1(attrMail,l)
            elif str(l.campaign)=='2' or str(l.campaign)=='3' or str(l.campaign)=='4' or str(l.campaign)=='5':
                attrMail=self.__prepareEmailCamp2(attrMail,l)
            elif str(l.campaign)=='7':
                attrMail=self.__prepareEmailCamp3(attrMail,l)
            else:
                self.log.error("campaña no reconocida:%s",l.campaign)
                attrMail = None
                

        except Exception,e:
            self.log.error("Error prepareEmail:  " + str(e) + "attributes: "+str(l))
            attrMail = None
        finally:
            return attrMail

    def __prepareEmailCamp3(self,attrMail,l):
        try:
            
            attrMail.strSubject=l.rest_name + ' - ¡Te presentamos nuestra nueva web!'
                
            hlink = 'http://irestauranting.com/home_resto.php?id_resto=%s&mail=1&camp=%s&intervalo=30d' % (l.id_Rest,l.campaign)
            if str(l.campaign)=='7':
                fp = open('template4.html', 'r')
            else:
                fp = open('template3.html', 'r')

            attrMail.strMsgHTML = fp.read()
            fp.close()
            
            #repetition of template1
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$rest_name$',l.rest_name)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$irest_link$',hlink)

            #añadir diccionario para imagenes
            """
            attrMail.listImages=[['img_header.png','<imgHeader>'],['earth70.jpg','<imgEarth>'],['two35.jpg','<imgTwo35>'],['newspapers.jpg','<imgNewspapers>'],['btnPruebalo.png','<imgBtnPruebalo>'],['facebook_circle_color.png','<imgFacebook>'],['twitter_circle_color.png','<imgTwitter>'],['linkedin_circle.png','<imgLinkedin>']]
            """
                
            if str(l.campaign)=='7':
                fp = open('template4.txt', 'r')
            else:
                fp = open('template3.txt', 'r')
                
            attrMail.strMsgASCII = fp.read()
            fp.close()
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$rest_name$',str(l.rest_name))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$irest_link$',hlink)

        except Exception,e:
            self.log.error("Error prepare Email3:  " + str(e) + "attributes: "+str(l))
            attrMail = None
        finally:
            return attrMail

    def __prepareEmailCamp2(self,attrMail,l):
        try:
            #need to clean up code... now campaign 2 is like campaing 1 plus posts
            scoreT= '%.1f' % Decimal(l.score)
            scorePR= '%.1f' % Decimal(l.score_presence)
            scoreOP= '%.1f' % Decimal(l.score_opinions)
            scoreAC= '%.1f' % Decimal(l.score_activity)
            
            #scoring de los posts
            SCORE_MIN = 6
            SCORE_MAX = 7.5
            dictNet={'ATRAPALO':'atrapalo.png','SALIR':'salir.png','YELP':'yelp.png','TRIPADVISOR':'trip.png','RESTALO':'restalo.png','TENEDOR':'tenedor.png'}
            dictFace={'RED':'face_red.png','ORANGE':'face_orange.png','GREEN':'face_green.png'}
            color=None

            if l.post1_score<SCORE_MIN:
                post1Face='RED'
                post1TitleStyle='color:#ff0000;'
            elif l.post1_score>SCORE_MAX:
                post1Face='GREEN'
                post1TitleStyle='color:#008000;'
            else:
                post1Face='ORANGE'
                post1TitleStyle='color:#fbb040;'

            if l.post2_score<SCORE_MIN:
                post2Face='RED'
                post2TitleStyle='color:#ff0000;'
            elif l.post2_score>SCORE_MAX:
                post2Face='GREEN'
                post2TitleStyle='color:#008000;'
            else:
                post2Face='ORANGE'
                post2TitleStyle='color:#fbb040;'


            if l.posts30 > 0:
                strPosts30= '%.0f' % Decimal(l.posts30)
                attrMail.strSubject=l.rest_name + ' ha tenido ' + str(strPosts30) + ' nuevas opiniones en los últimos 30 días'
            else:
                attrMail.strSubject=l.rest_name + ' has tenido nuevas opiniones de tu restaurante'
                
            hlink = 'http://irestauranting.com/home_resto.php?id_resto=%s&mail=1&camp=%s&intervalo=30d' % (l.id_Rest,l.campaign)
            if str(l.campaign)=='2' or str(l.campaign)=='3':
                fp = open('template2.html', 'r')
            else:
                fp = open('template3.html', 'r')
            attrMail.strMsgHTML = fp.read()
            fp.close()
            if l.posts30 > 0:
                strH1 ='El restaurante <span > <a style="color:#ff8c00;text-decoration:none" target="_blank" href=%s> %s </a> </span> ha recibido <span> <a style="color:#ff8c00;text-decoration:none" target="_blank" href=%s> %s </a> </span> nuevas opiniones en los últimos 30 días' % (hlink, str(l.rest_name),hlink,str(strPosts30) )
            else:
                strH1= 'El restaurante <span> <a style="color:#ff8c00;text-decoration:none" target="_blank" href=%s> %s </a> </span> ha recibido nuevas opiniones ' % (hlink,str(l.rest_name))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$h1$',strH1)
            if l.post1_title is None:
                strTitle1=''
            else:
                strTitle1 = ' <div style="margin-bottom:5px;"> <span  style="font-size:18px;font-weight:bold;%s;text-decoration: none;">%s</span> </div>' %(post1TitleStyle,str(l.post1_title))
            if l.post2_title is None or len(l.post2_title)==0:
                strTitle2=''
            else:
                strTitle2 = ' <div style="margin-bottom:5px;"> <span  style="font-size:18px;font-weight:bold;%s;text-decoration: none;">%s</span> </div>' %(post2TitleStyle,str(l.post2_title))
                
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post1_title$',strTitle1)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post2_title$',strTitle2)

            #repetition of template1
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$rest_name$',l.rest_name)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score$',scoreT)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_p$',scorePR)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_o$',scoreOP)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_a$',scoreAC)

            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post1_date$',l.post1_date.strftime('%d-%m-%Y'))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post2_date$',l.post2_date.strftime('%d-%m-%Y'))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post1_text$',str(l.post1_text))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post2_text$',str(l.post2_text))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post1_stars$',self.__getHtmlStars(l.post1_score))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$post2_stars$',self.__getHtmlStars(l.post2_score))
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$irest_link$',hlink)

            #añadir diccionario para imagenes
            #attrMail.listImages=[['LogoHome.png','<LogoHome>'],['BotonC2.png','<Boton>'],[dictNet[l.post1_net],'<ImgNet1>'], [dictNet[l.post2_net],'<ImgNet2>'],[dictFace[post1Face],'<ImgFace1>'],[dictFace[post2Face],'<ImgFace2>'],['star_full.png','<StarFull>'],['star_mid.png','<StarMid>'],['star_empty.png','<StarEmpty>']]
            attrMail.listImages=[['LogoHome.png','<LogoHome>'],['BotonC2.png','<Boton>'],[dictNet[l.post1_net],'<ImgNet1>'], [dictNet[l.post2_net],'<ImgNet2>'],['star_full.png','<StarFull>'],['star_mid.png','<StarMid>'],['star_empty.png','<StarEmpty>']]

            if str(l.campaign)=='2' or str(l.campaign)=='3':
                fp = open('template2.txt', 'r')
            else:
                fp = open('template3.txt', 'r')
                
            attrMail.strMsgASCII = fp.read()
            fp.close()
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$rest_name$',str(l.rest_name))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post1_date$',l.post1_date.strftime('%d-%m-%Y'))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post2_date$',l.post2_date.strftime('%d-%m-%Y'))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post1_net$',l.post1_net.title())
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post2_net$',l.post2_net.title())
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post1_text$',str(l.post1_text))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$post2_text$',str(l.post2_text))
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$irest_link$',hlink)

            #repetition of template1
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score$',scoreT)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_p$',scorePR)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_o$',scoreOP)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_a$',scoreAC)
                               
        except Exception,e:
            self.log.error("Error prepare Email2:  " + str(e) + "attributes: "+str(l))
            attrMail = None
        finally:
            return attrMail

    def __prepareEmailCamp1(self,attrMail,l):
        try:
            scoreT= '%.1f' % Decimal(l.score)
            scorePR= '%.1f' % Decimal(l.score_presence)
            scoreOP= '%.1f' % Decimal(l.score_opinions)
            scoreAC= '%.1f' % Decimal(l.score_activity)               
            
            attrMail.strSubject=restName + ' tiene una valoración de ' + scoreT + ' en Internet'
            hlink = 'http://irestauranting.com/home_resto.php?id_resto=%s&mail=1&camp=%s&intervalo=30d' % (l.id_Rest,l.campaign) 
            fp = open('template.txt', 'r')
            attrMail.strMsgASCII = fp.read()
            fp.close()

            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$rest_name$',l.rest_name)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score$',scoreT)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_p$',scorePR)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_o$',scoreOP)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$score_a$',scoreAC)
            attrMail.strMsgASCII=attrMail.strMsgASCII.replace('$irest_link$',hlink)


            fp = open('template.html', 'r')
            attrMail.strMsgHTML = fp.read()
            fp.close()
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$rest_name$',l.rest_name)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score$',scoreT)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_p$',scorePR)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_o$',scoreOP)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$score_a$',scoreAC)
            attrMail.strMsgHTML=attrMail.strMsgHTML.replace('$irest_link$',hlink)
                
            attrMail.listImages=[['LogoHome.png','<LogoHome>'],['Boton.png','<Boton>']]
        except Exception,e:
            self.log.error("Error prepareEmail1:  " + str(e) + "attributes: "+str(l))
            attrMail = None
        finally:
            return attrMail

            

    def __getHtmlStars(self,score):

        html = ''
        cont_star = 0

        while(score > 0):
            if(score >= 1):
                html = html + '<img width="15" height="15" src="cid:StarFull" />'
            else:
                html = html + '<img width="15" height="15" src="cid:StarMid" />'
            score = score - 2
            cont_star=cont_star+1

        while(cont_star < 5):
            html = html + '<img width="15" height="15" src="cid:StarEmpty" />';
            cont_star=cont_star+1


        return html
    
    def sendEmail(self,attrMail):
        try:
            # Create the root message and fill in the from, to, and subject headers
            msgRoot = MIMEMultipart('related')
            msgRoot['Subject'] = Header(attrMail.strSubject.encode('utf-8'),"utf-8")
            msgRoot['From'] = attrMail.strFrom
            msgRoot['To'] = ",".join(attrMail.lTo) 
            msgRoot.preamble = 'This is a multi-part message in MIME format.'

            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)

            msgText = MIMEText(attrMail.strMsgASCII.encode('utf-8'),'plain','UTF-8')
            msgAlternative.attach(msgText)

            # We reference the image in the IMG SRC attribute by the ID we give it below
            msgText = MIMEText(attrMail.strMsgHTML.encode('utf-8'), 'html','UTF-8')
            msgAlternative.attach(msgText)

            # This example assumes the image is in the current directory
            for i in attrMail.listImages:
                fp = open(i[0], 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', i[1])
                msgRoot.attach(msgImage)


            # Send the email (this example assumes SMTP authentication is required)
            smtp = smtplib.SMTP()
            smtp.connect(attrMail.strSMTP)
            smtp.login(attrMail.strUser, attrMail.strPwd)
            smtp.sendmail(attrMail.strFrom, attrMail.lTo, msgRoot.as_string())
            smtp.quit()
            return True
        except Exception,e:
            self.log.error("Error sendEmail:  " + str(e) + "attributes: " + str(attrMail))
            return False
        

def __init(log):
    try:
        reload(sys)
        sys.setdefaultencoding('utf-8')
        time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        filename = time + '.log'
        filename = os.path.join('logEmailMarketing/',filename)
        handler = logging.FileHandler(filename)
        handler2 = logging.StreamHandler(sys.stdout)
        # create a logging format
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        handler2.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)
        handler2.setLevel(logging.DEBUG)

        # add the handlers to the logger
        log = logging.getLogger('EmailMarketing')
        log.setLevel(logging.DEBUG)
        log.addHandler(handler)
        log.addHandler(handler2)


        return log
    except Exception,e:
        print "Error en __init: " + str(e)     

def main():
    numEmails=0
    log=None
    db=None
    #set active campaign
    numCampaign=7
    
    try:
        log = __init(log)
        db = DB(log)
        db.connectDB()
        
        
        emailMarketing = EmailMarketing(log)

        lcampaignRest = db.getCampaingsDetails(numCampaign)
     
        for l in lcampaignRest:
            log.debug("Ini marketing campaign: %s",str(l.campaign))
            attrMail = emailMarketing.prepareEmail(l)
            if attrMail is not None:
                if emailMarketing.sendEmail(attrMail):
                    log.info("Email mandado correctamente para campana: %s, restaurante: %s, email: %s", l.campaign,l.rest_name,l.email)
                    numEmails =numEmails +1
                    db.campaignSent(l.campaign, l.id_Rest)
                else:
                    log.error("Error al intentar mandar mandar email para campana: %s, restaurante: %s, email: %s", l.campaign,l.rest_name,l.email)   
            else:
                log.error("No se ha podido rellenar email para campana: %s, restaurante: %s, email: %s", l.campaign,l.rest_name,l.email)
            

        log.info("Total emails: %s",str(numEmails))
        

    except Exception,e:
        log.error("Error en Main: " + str(e))
    finally:
        return



if __name__ == "__main__":
    main() 
